import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:thermal_printer/esc_pos_utils_platform/esc_pos_utils_platform.dart';
import 'package:thermal_printer/esc_pos_utils_platform/src/capability_profile.dart';
import 'package:thermal_printer/esc_pos_utils_platform/src/enums.dart';
import 'package:thermal_printer/esc_pos_utils_platform/src/generator.dart';
import 'package:thermal_printer/esc_pos_utils_platform/src/pos_column.dart';
import 'package:thermal_printer/esc_pos_utils_platform/src/pos_styles.dart';
import 'package:thermal_printer/thermal_printer.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  _print() async {
    List<int> bytes = [];

    // Xprinter XP-N160I
    final profile = await CapabilityProfile.load();

    // PaperSize.mm80 or PaperSize.mm58
    final generator = Generator(PaperSize.mm58, profile);
    bytes += generator.text(
      '大润发',
      styles: const PosStyles(
        align: PosAlign.center,
        width: PosTextSize.size3,
        height: PosTextSize.size3,
        bold: true,
      ),
      containsChinese: true,
    );
    bytes += generator.text('豆浆机', containsChinese: true);
    bytes += generator.text('洗衣液', containsChinese: true);

    bytes += generator.text('￥1,990',
        containsChinese: true, styles: const PosStyles(align: PosAlign.left));
    bytes += generator.emptyLines(1);

    // sum width total column must be 12
    bytes += generator.row([
      PosColumn(
          width: 8,
          text: '豆浆机',
          styles: const PosStyles(align: PosAlign.left, codeTable: 'CP1252'),
          containsChinese: true),
      PosColumn(
          width: 4,
          text: '289.00',
          styles: const PosStyles(align: PosAlign.right, codeTable: 'CP1252')),
    ]);

    // // Chinese characters
    bytes += generator.row([
      PosColumn(
          width: 8,
          text: '洗衣液',
          styles: const PosStyles(align: PosAlign.left),
          containsChinese: true),
      PosColumn(
          width: 4,
          text: '69.80',
          styles: const PosStyles(align: PosAlign.right),
          containsChinese: true),
    ]);
    await PrinterManager.instance
        .connect(model: UsbPrinterInput(name: "XP-58"));
    await PrinterManager.instance.print(bytes);
    await PrinterManager.instance.disconnect();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () {
                  _print();
                },
                child: const Text("打印"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
